package khfx.dao.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import khfx.util.Config;
import org.apache.log4j.Logger;
import com.ibm.db2.jcc.DB2DataSource;
/**
 * 
 * @author wanglong635@126.com
 *
 */
public class StoreManager {
	final private static Logger logger = Logger.getLogger(StoreManager.class);
	private static DataSource ds = null;

	public static void init() {
		String jndi_name = Config.getConfig("jndi.datasource.name");
		if (jndi_name == null || jndi_name.length() == 0) {
			String dc = Config.getConfig("database.connection");
			String[] db = dc.split(":");
			if(db.length!=5){
				logger.error("Database connection error!");
				return;
			} else {
				if(logger.isDebugEnabled()){
					logger.debug("ServerName=" + db[0] + ",portNumber=" + db[1] + 
							  ",database=" + db[2] + ",user=" + db[3] +",password=" + db[4]);
				}
			}
			
			DB2DataSource db2ds = new DB2DataSource();// which has built-in
			// support
			// for connection pooling.
			// Create DataSource object

			db2ds.setServerName(db[0]);
			db2ds.setPortNumber(Integer.parseInt(db[1]));
			db2ds.setDatabaseName(db[2]); // Set location
			db2ds.setUser(db[3]);
			db2ds.setPassword(db[4]);
			db2ds.setDriverType(4);

			ds = db2ds;
		} else {
			try {
				Context cntxt = new InitialContext();
				ds = (DataSource) cntxt.lookup(jndi_name);
			} catch (NamingException e) {
				logger.error("Can't initial datasource", e);
				ds = null;
			}
		}
	}

	public static Session openSession() {
		if (ds == null) {
			init();
		}
		Session session = null;
		try {
			session = new Session(ds.getConnection());
		} catch (SQLException e) {
			logger.error("Open session error!", e);
		}
		return session;
	}

	public static void closeSession(Session session) {
		if (session != null)
			session.close();
	}

	public static ResultSet queryList(String sql) {
		Connection conn = null;

		PreparedStatement stmt;
		try {
			conn = ds.getConnection();
			conn
					.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
			stmt = conn.prepareStatement(sql);
			ResultSet rs = stmt.executeQuery();

			return rs;

		} catch (SQLException e) {
			e.printStackTrace();
		}

		return null;

	}

	public static void main(String[] args) {
		StoreManager.openSession();
	}
}
